<template>
  <div class="big-box">
    <div id="cesiumContainer" class="cesiumMapContainer"></div>
  </div>
</template>

<script setup>
import * as Cesium from "cesium";
import DefaultGlobe from "@/utils/default-globe.js";
import { DynamicWallMaterialProperty } from "@/utils/flowWallCesium.js";
import { ImageLineMaterial } from "@/utils/flowlineCesium.js";
import { CircleRippleMaterialProperty } from "@/utils/wavepoiCesium.js";
import { FireEffect } from "@/utils/firePartice.js";
import { onMounted } from "vue";
import { useStore } from "vuex";
let store = useStore();

import axios from "axios";

let wmsList = [
  {
    url: "geoserver/test/wms?service=WMS&version=1.1.0&request=GetMap&layers=test%3Acqa&bbox=105.28983805000016%2C28.164713309999993%2C110.19563242500007%2C32.20417072500006&width=768&height=632&srs=EPSG%3A4326&styles=&format=application/openlayers",
    layerName: "test:cqa",
  },
  {
    url: "geoserver/test/wms?service=WMS&version=1.1.0&request=GetMap&layers=test%3Achinaa&bbox=73.502355%2C3.39716187%2C135.09567%2C53.563269&width=768&height=625&srs=EPSG%3A4326&styles=&format=application/openlayers",
    layerName: "test:chinaa",
  },
];

let wmtsList = [
  {
    url: "geoserver/test/wms?service=WMS&version=1.1.0&request=GetMap&layers=test%3AcqImg&bbox=105.28472900390625%2C28.164138793945312%2C110.19355773925781%2C32.20367431640625&width=768&height=631&srs=EPSG%3A4326&styles=&format=application/openlayers",
    layerName: "test:cqImg",
  },
];

let tileList = [
  {
    url: "src/assets/data/3dtiles/fwBm1/tileset.json",
  },
];

let geoList = [
  {
    name: "区域道路",
    url: "src/assets/data/vec/roada.json",
  },
  {
    name: "区域范围",
    // url: "src/assets/data/vec/xiaoqua.json",
    url: "src/assets/data/vec/xiaoqul.json",
  },
  {
    name: "流动线",
    url: "src/assets/data/vec/flowline.json",
  },
  {
    name: "水波纹",
    url: "src/assets/data/vec/startPois.json",
  },
];
onMounted(() => {
  // 初始化地图
  initViewer();
  // 左键点击事件
  leftClickEvent();

  // 添加3dtiles
  add3dtiles(tileList[0].url);

  // 添加geojson
  addGeoEntLayer(geoList[0].url, { id: "qydl" });

  // 添加围墙
  addWallGeoLayer(geoList[1].url);

  // 添加中心点
  addAreaCenter();

  // 添加流动线
  addFlowGeoLayer(geoList[2].url);

  // 添加水波纹点
  addWavePoi(geoList[3].url);
});
// 初始化 viewer
let viewer = null;
function initViewer() {
  viewer = new Cesium.Viewer("cesiumContainer", {
    geocoder: false, //隐藏查找控件
    homeButton: false, //隐藏视角返回初始位置按钮
    sceneModePicker: false, //隐藏视角模式3D 2D CV
    baseLayerPicker: false, //隐藏图层选择
    navigationHelpButton: false, //隐藏帮助
    animation: false, //隐藏动画控件
    timeline: false, //隐藏时间线控件
    fullscreenButton: false, //隐藏全屏
    selectionIndicator: false, // 关闭点击绿色框
    // terrain: Cesium.Terrain.fromWorldTerrain(), // 地形
    infoBox: false, // 关闭 信息提示框
  });
  // 隐藏版权信息
  viewer._cesiumWidget._creditContainer.style.display = "none";
  DefaultGlobe.cesiumDefaultModel(viewer);
  store.state.viewer = viewer;
  window.viewer = viewer;
  window.Cesium = Cesium;
}

// 添加矢量geojson
/*
 * @param {String} url geojson文件地址
 * @param {Object} option 配置项
 * @param {Color} option.outlineColor 边框颜色
 * @param {Color} option.fillColor 填充颜色
 * @param {Bolean} option.clampToGround 是否贴地
 */
function addGeoEntLayer(url, option) {
  Cesium.GeoJsonDataSource.load(url, {}).then((dataSource) => {
    viewer.dataSources.add(dataSource);
    dataSource.entities.values.forEach((entity) => {
      if (option.id == "center") {
        entity.label = {
          text: entity.properties.areaName,
          font: "14pt Source Han Sans CN", //字体样式
          fillColor: Cesium.Color.BLACK, //字体颜色
          backgroundColor: Cesium.Color.AQUA, //背景颜色
          showBackground: true, //是否显示背景颜色
          style: Cesium.LabelStyle.FILL, //label样式
          outlineWidth: 2,
          verticalOrigin: Cesium.VerticalOrigin.CENTER, //垂直位置
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER, //水平位置
          zIndex: 99,
          disableDepthTestDistance: Number.POSITIVE_INFINITY,
          pixelOffset: new Cesium.Cartesian2(0, -80), // 调整标签位置
        };
        entity.billboard = {
          image: "src/assets/images/cesium/poiLine2.png", //修改图片样式
          scale: 0.5, //图片缩放大小
          zIndex: 99,
          // clampToGround: true,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        };
      } else if (option.id == "qydl") {
        entity.polygon.clampToGround = true;
        entity.polygon.material = Cesium.Color.YELLOW.withAlpha(0.8);
        entity.polygon.outline = Cesium.Color.YELLOW.withAlpha(0.8);
      }
    });
  });
}

// 添加围墙
function addWall(positions, index) {
  let url = "src/assets/images/cesium/wallPic-blue.png";
  index = 3;
  if (index == 1) {
    url = "src/assets/images/cesium/wallPic-blue.png";
  } else if (index == 3) {
    url = "src/assets/images/cesium/wallPic-green.png";
  } else if (index == 6) {
    url = "src/assets/images/cesium/wallPic-red.png";
  }
  viewer.entities.add({
    name: "dynamicWall",
    wall: {
      positions: positions,
      // 设置高度
      maximumHeights: new Array(positions.length).fill(50),
      minimumHeights: new Array(positions.length).fill(0),
      material: new DynamicWallMaterialProperty({
        color: Cesium.Color.fromBytes(55, 96, 56).withAlpha(0.7),
        duration: 3000,
        trailImage: url,
      }),
    },
  });
}
// 添加流动围墙
function addWallGeoLayer(url) {
  axios.get(url).then((res) => {
    res.data.features.forEach((item, index) => {
      let poiList = item.geometry.coordinates[0];
      poiList.push(poiList[0]);
      let positions = [];
      poiList.forEach((poi) => {
        positions.push(poi[0]);
        positions.push(poi[1]);
      });

      positions = Cesium.Cartesian3.fromDegreesArray(positions);
      addWall(positions, item.properties.type);
    });
  });
}

// 添加区域中心
function addAreaCenter() {
  let poiUrl = "src/assets/data/vec/areacp.json";
  let option = {
    id: "center",
  };
  addGeoEntLayer(poiUrl, option);
}

// 添加流动线
function addFlowGeoLayer(url) {
  Cesium.GeoJsonDataSource.load(url, {}).then((dataSource) => {
    viewer.dataSources.add(dataSource);
    dataSource.entities.values.forEach((entity) => {
      if (entity.polyline) {
        entity.polyline.width = 16;
        entity.polyline.clampToGround = true;
        entity.polyline.material = new ImageLineMaterial();
      }
    });
  });
}

// 添加水波纹
function addWavePoi(url) {
  axios.get(url).then((res) => {
    let poiList = res.data.features;
    poiList.forEach((item, index) => {
      let positions = item.geometry.coordinates;
      // 添加水波纹特效
      viewer.entities.add({
        position: Cesium.Cartesian3.fromDegrees(positions[0], positions[1], 50),
        name: "波纹圆" + index,
        ellipse: {
          semiMinorAxis: 100.0,
          semiMajorAxis: 100.0,
          material: new CircleRippleMaterialProperty({
            color: new Cesium.Color.fromCssColorString(
              "rgba(120, 255, 198, 0.6)"
            ),
            speed: 24.0,
            count: 4,
            gradient: 0,
          }),
        },
        billboard: {
          image: "src/assets/images/cesium/point-marker.png", //修改图片样式
          scale: 0.2, //图片缩放大小
          zIndex: 99,
          // clampToGround: true,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        },
      });
    });
  });
}

// 添加起火点
function addFirePoi() {
  let fire = new FireEffect(viewer)

}

// 添加冒烟点
function addSmokePoi() {}
// 添加图层
function addWmsLayer(url, layers) {
  viewer.imageryLayers.addImageryProvider(
    new Cesium.WebMapServiceImageryProvider({
      url: url,
      layers: layers, //'数据源:图层名'
      parameters: {
        service: "WMS",
        format: "image/png", //返回格式为png格式
        transparent: true,
        srs: "EPSG:4326",
        style: "",
      },
    })
  );
}

//添加WMTS方法 传入url 和 图层名称
function addWmtsLayer(url, layer) {
  viewer.imageryLayers.addImageryProvider(
    new Cesium.WebMapTileServiceImageryProvider({
      url: url,
      layer: layer,
      style: "default",
      format: "image/jpeg",
      tileMatrixSetID: "EPSG:4326",
      tileMatrixLabels: [
        "0",
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
        "10",
        "11",
        "12",
        "13",
        "14",
        "15",
        "16",
        "17",
        "18",
        "19",
        "20",
        "21",
        "22",
        "23",
      ],
    })
  );
}

// 添加3dtiles
function add3dtiles(url) {
  Cesium.Cesium3DTileset.fromUrl(url, {
    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
    clampToGround: true,
  }).then((tilesets) => {
    // this.store.state.tileset = tilesets;
    viewer.scene.primitives.add(tilesets);
  });
}

// 左键点击事件
function leftClickEvent() {
  let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  let that = this;
  handler.setInputAction(async (movement) => {
    // console.log(selectEntity);
    let pick = viewer.scene.pick(movement.position);
    console.log(pick);

    if (Cesium.defined(pick)) {
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
}
</script>

<style scoped>
.cesiumMapContainer {
  width: 100%;
  height: 100%;
}
</style>